async function request(config: {
  url: string;
  data?: any;
  headers?: any;
  method: 'post' | 'get' | 'put' | 'patch' | 'delete';
  onProgress?: (e?: any) => void;
  requestList?: XMLHttpRequest[];
}) {
  const {
    data,
    headers = {},
    method,
    url,
    onProgress = () => {},
    requestList,
  } = config || {};
  return new Promise((resolve) => {
    const xhr = new XMLHttpRequest();

    xhr.upload.onprogress = onProgress;

    xhr.open(method, url);

    for (const key in headers) {
      xhr.setRequestHeader(key, headers[key]);
    }

    xhr.send(data);

    xhr.onload = () => {
      // 请求成功的 xhr 从数组中移除
      if (requestList) {
        const xhrIndex = requestList.findIndex(
          (item: XMLHttpRequest) => item === xhr,
        );
        requestList.splice(xhrIndex, 1);
      }
      resolve(xhr.response);
    };

    // 暴露当前 xhr 给外部
    requestList?.push(xhr);
  });
}

export default request;
